package com.example.note2;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import androidx.appcompat.widget.SearchView; // 正确的导入
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.activity.EdgeToEdge;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    final String TAG = "MainActivity";
    private FloatingActionButton fab;
    private ListView listView;
    private NoteAdapter adapter;
    private List<Note> noteList = new ArrayList<>();
    private Toolbar myToolbar;

    // 用户相关变量
    private String currentUsername;
    private String currentUserId; // 当前用户ID
    private CRUD op; // CRUD 操作对象

    // 弹出菜单
    private PopupWindow popupWindow;
    private PopupWindow popupCover;
    private ViewGroup customView;
    private ViewGroup coverView;
    private LayoutInflater layoutInflater; // 渲染布局
    private RelativeLayout main;
    private WindowManager wm;
    private DisplayMetrics metrics;
    private TextView setting_text;
    private ImageView setting_image;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CRUD crud = new CRUD(this);
        crud.open();

        currentUsername = getIntent().getStringExtra("username"); // 获取用户 ID
        String userId = String.valueOf(crud.getUserIdByUsername(currentUsername));
        currentUserId = userId;
        Log.d(TAG, "Current User ID: " + userId); // 显示用户 ID
        Log.d(TAG, "onCreate: Start MainActivity"); // 添加日志
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);



        if (currentUserId == null || currentUserId.isEmpty()) {
            Toast.makeText(this, "用户信息无效", Toast.LENGTH_SHORT).show();

        }

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        fab = findViewById(R.id.floatingActionButton);
        listView = findViewById(R.id.lv);
        myToolbar = findViewById(R.id.toolbar);
        adapter = new NoteAdapter(this, noteList);
        listView.setAdapter(adapter);

        setSupportActionBar(myToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        initPopUpView(); // 实例化弹出菜单
        myToolbar.setNavigationIcon(R.drawable.ic_menu_24);
        myToolbar.setNavigationOnClickListener(v -> showPopUpView(v));

        listView.setOnItemClickListener(this);

        fab.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, EditActivity.class);
            intent.putExtra("mode", 4); // 新建笔记模式
            intent.putExtra("user_id", currentUserId); // 传递用户ID
            startActivityForResult(intent, 0);
        });

        op = new CRUD(this); // 初始化 CRUD 操作对象
        refreshListView(); // 刷新列表
    }

    // 弹出菜单
    public void initPopUpView() {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        customView = (ViewGroup) layoutInflater.inflate(R.layout.setting_layout, null);
        coverView = (ViewGroup) layoutInflater.inflate(R.layout.setting_cover, null);
        main = findViewById(R.id.main);
        wm = getWindowManager();
        metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
    }

    // 获得页面宽高
    public void showPopUpView(View view) {
        int width = metrics.widthPixels;
        int height = metrics.heightPixels;

        popupCover = new PopupWindow(coverView, width, height, false);
        popupWindow = new PopupWindow(customView, (int) (width * 0.7), height);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

        findViewById(R.id.main).post(() -> {
            popupCover.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);
            popupWindow.showAtLocation(main, Gravity.NO_GRAVITY, 0, 0);

            setting_image = customView.findViewById(R.id.setting_setting_image);
            setting_text = customView.findViewById(R.id.setting_setting_text);

            setting_image.setOnClickListener(v -> {
                Intent intent = new Intent(MainActivity.this, UserSettingsActivity.class);
                startActivity(intent);
            });

            coverView.setOnTouchListener((v, event) -> {
                popupWindow.dismiss();
                return true;
            });

            popupWindow.setOnDismissListener(() -> popupCover.dismiss());
        });
    }

    // 刷新 ListView
    private void refreshListView() {
        op.open();
        if (noteList.size() > 0) noteList.clear();
        noteList.addAll(op.getAllNotes(currentUserId)); // 获取当前用户的所有笔记
        op.close();
        adapter.notifyDataSetChanged();
    }

    // 接受 startActivityForResult 结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            int returnMode = data.getExtras().getInt("mode", -1);
            long note_Id = data.getExtras().getLong("id", 0);

            if (returnMode == 1) { // 更新笔记
                String content = data.getExtras().getString("content");
                String time = data.getExtras().getString("time");
                int tag = data.getExtras().getInt("tag", 1);

                Note updatedNote = new Note(content, time, tag, currentUserId); // 新增用户ID处理
                updatedNote.setId(note_Id);
                op.open();
                op.updateNote(updatedNote);
                op.close();
            } else if (returnMode == 0) { // 新建笔记
                String content = data.getExtras().getString("content");
                String time = data.getExtras().getString("time");
                int tag = data.getExtras().getInt("tag", 1);

                Note newNote = new Note(content, time, tag, currentUserId); // 新增用户ID处理
                op.open();
                op.addNote(newNote);
                op.close();
            } else if (returnMode == 2) { // 删除笔记
                Note curNote = new Note();
                curNote.setId(note_Id);
                op.open();
                op.removeNote(curNote);
                op.close();
            } else { // 没有修改笔记
                Log.w(TAG, "No valid data received or operation was cancelled.");
            }
            refreshListView();
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        MenuItem mSearch = menu.findItem(R.id.menu_search);
        SearchView mSearchView = (SearchView) mSearch.getActionView();

        mSearchView.setQueryHint("搜索笔记");
        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Log.d(TAG, "Search submitted: " + query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                adapter.getFilter().filter(newText);
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.menu_clear) {
            new AlertDialog.Builder(MainActivity.this)
                    .setMessage("确定清空所有笔记吗？")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            op.open();
                            SQLiteDatabase db = op.dbHandler.getWritableDatabase();
                            db.delete(NoteDatabase.TABLE_NAME, NoteDatabase.USER_ID + "=?", new String[]{currentUserId}); // 仅删除当前用户的笔记
                            op.close();
                            refreshListView();
                        }
                    })
                    .setNegativeButton(android.R.string.no, (dialogInterface, i) -> dialogInterface.dismiss())
                    .create().show();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.lv) {
            Note curNote = (Note) parent.getItemAtPosition(position);
            Intent intent = new Intent(MainActivity.this, EditActivity.class);
            intent.putExtra("content", curNote.getContent());
            intent.putExtra("id", curNote.getId());
            intent.putExtra("time", curNote.getTime());
            intent.putExtra("mode", 3);
            intent.putExtra("tag", curNote.getTag());
            intent.putExtra("user_id", currentUserId); // 传递用户ID
            startActivityForResult(intent, 1);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setNightMode(); // 每次返回时都检查夜间模式设置
    }
}
